/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.tarena.lbs.attach.rpc;

import com.tarena.lbs.attach.api.AttachApi;
import com.tarena.lbs.attach.config.MinioConfig;
import com.tarena.lbs.attach.pojo.dto.AttachDTO;
import com.tarena.lbs.attach.pojo.dto.AttachQrDTO;
import com.tarena.lbs.attach.pojo.param.AttachQRParam;
import com.tarena.lbs.attach.pojo.param.PicUpdateParam;
import com.tarena.lbs.attach.pojo.query.AttachQuery;
import com.tarena.lbs.attach.utils.QRCodeUtil;
import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

@DubboService
@Slf4j
@Service
public class AttachRpcService implements AttachApi {
    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConfig minioConfig;

    @Override
    public List<AttachDTO> getAttachInfo(AttachQuery attachQuery) {
        return Collections.emptyList();
    }

    @Override
    public boolean batchUpdateBusiness(List<PicUpdateParam> picParams) {
        return false;
    }

    @Override
    public AttachQrDTO generateQrCode(AttachQRParam attachQRParam) throws Exception {
//        minio存储桶名
        String bucketName = "lbs-attach-web-qrcode";

        String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase(Locale.ROOT);

//        判断桶是否存在
        boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
//        桶不存在则创建
        if (!bucketExists) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(createBucketPolicyConfig(bucketName)).build());
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        QRCodeUtil.createCodeToOutputStream(attachQRParam.getContent(), outputStream);
        ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());

//        上传文件到minio
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(uuid)
                .stream(inputStream, inputStream.available(), -1)
                .contentType("image/png")
                .build());

        AttachQrDTO attachQrDTO = new AttachQrDTO();
        attachQrDTO.setUrl("%s/%s/%s".formatted(minioConfig.getEndpoint(), bucketName, uuid));

        return attachQrDTO;
    }

    private String createBucketPolicyConfig(String bucketName) {
        return """
                {
                  "Statement" : [ {
                    "Action" : "s3:GetObject",
                    "Effect" : "Allow",
                    "Principal" : "*",
                    "Resource" : "arn:aws:s3:::%s/*"
                  } ],
                  "Version" : "2012-10-17"
                }
                """.formatted(bucketName);
    }
}
